package com.example.jeong.yuejian10.Activity;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jeong.yuejian10.Bean.AttentionBean;
import com.example.jeong.yuejian10.Bean.IsAttentionBean;
import com.example.jeong.yuejian10.Model.TrainModel;
import com.example.jeong.yuejian10.R;
import com.squareup.picasso.Picasso;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.example.jeong.yuejian10.constant.Constant.TRAIN_PHOTO_URL;

//训练详情页
public class TrainDetailActivity extends Activity {
    private ImageView left;
    private ImageView collect;
    private ImageView t_picture;
    private TextView t_name;
    private TextView t_address;
    private TextView t_time;
    private TextView t_price;
    private TextView t_phone;
    private Button zixun;
    private Button baoming;
    private int u_id;

    private String coresult="";
    private int t_id;
    private String flag;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_train_detail);
        SharedPreferences sp = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        u_id = sp.getInt("u_id", 0);
        initView();
        initEvents();
        getTrainData();
        isBeCollected();

    }

    private void initView() {

        collect = (ImageView) findViewById(R.id.collect);
        left = (ImageView) findViewById(R.id.left);
        t_name = (TextView) findViewById(R.id.name);
        t_address = (TextView) findViewById(R.id.t_address);
        t_time = (TextView) findViewById(R.id.time);
        t_price = (TextView) findViewById(R.id.price);
        t_phone = (TextView) findViewById(R.id.t_phone);
        t_picture=(ImageView) findViewById(R.id.t_picture) ;
        zixun=(Button) findViewById(R.id.zixun) ;
        baoming=(Button) findViewById(R.id.baoming) ;
    }
    public void initEvents(){

        //返回上一页
        left.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        t_id=getIntent().getIntExtra("t_id",-1);

        baoming.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(TrainDetailActivity.this, EnterTrainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("t_id", t_id);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                collectTrain();
            }
        });

        //  立即咨询-一键打电话
        zixun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查是否获得了权限（Android6.0运行时权限）
                if (ContextCompat.checkSelfPermission(TrainDetailActivity.this,
                        Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
                    // 没有获得授权，申请授权
                    if (ActivityCompat.shouldShowRequestPermissionRationale(TrainDetailActivity.this,
                            Manifest.permission.CALL_PHONE)) {
                        // 返回值：
//                          如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
//                          如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
//                          如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                        // 弹窗需要解释为何需要该权限，再次请求授权
                        Toast.makeText(TrainDetailActivity.this, "请授权！", Toast.LENGTH_LONG).show();

                        // 帮跳转到该应用的设置界面，让用户手动授权
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        startActivity(intent);
                    }else{
                        // 不需要解释为何需要该权限，直接请求授权
                        ActivityCompat.requestPermissions(TrainDetailActivity.this,
                                new String[]{Manifest.permission.CALL_PHONE},
                                MY_PERMISSIONS_REQUEST_CALL_PHONE);
                    }
                }else {
                    // 已经获得授权，可以打电话
                    CallPhone();
                }
            }
        });



    }

    private void CallPhone() {
        String number = t_phone.getText().toString();
        if (TextUtils.isEmpty(number)) {
            // 提醒用户
            // 注意：在这个匿名内部类中如果用this则表示是View.OnClickListener类的对象，
            // 所以必须用MainActivity.this来指定上下文环境。
            Toast.makeText(TrainDetailActivity.this, "号码不能为空！", Toast.LENGTH_SHORT).show();
        } else {
            // 拨号：激活系统的拨号组件
            Intent intent = new Intent(); // 意图对象：动作 + 数据
            intent.setAction(Intent.ACTION_CALL); // 设置动作
            Uri data = Uri.parse("tel:" + number); // 设置数据
            intent.setData(data);
            startActivity(intent); // 激活Activity组件
        }
    }

    // 处理权限申请的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_CALL_PHONE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功，继续打电话
                    CallPhone();
                } else {
                    // 授权失败！
                    Toast.makeText(this, "授权失败！", Toast.LENGTH_LONG).show();
                }
                break;
            }
        }

    }

    //获取培训详情数据
    private void getTrainData() {
        Bundle bundle = this.getIntent().getExtras();
        int t_id = bundle.getInt("t_id");
        String tname = bundle.getString("t_name");
        String taddress = bundle.getString("t_address");
        String tphone = bundle.getString("t_phone");
        int tprice = bundle.getInt("t_price");

        String tpicture = TRAIN_PHOTO_URL+bundle.getString("t_picture");
        String ttime = bundle.getString("t_time");
        t_name.setText(tname);
        t_address.setText(taddress);
        t_phone.setText(tphone);
        t_price.setText(tprice+"");
        t_time.setText(ttime);
        Picasso.with(this).load(tpicture).into(t_picture);
    }


    private void isBeCollected(){

        //判断是否关注
        TrainModel trainModel=new TrainModel();
        Call<IsAttentionBean> callIsCollect=trainModel.getIsCollected(u_id,t_id,"0");

        callIsCollect.enqueue(new Callback<IsAttentionBean>() {
            @Override
            public void onResponse(Call<IsAttentionBean> call, Response<IsAttentionBean> response) {
                String result=response.body().getCollected();
                if ("0".equals(result)) {

                    collect.setImageResource(R.drawable.ic_collect_hui);
                    coresult = "no";
                } else {
                    coresult = "yes";
                    collect.setImageResource(R.drawable.ic_collect_red);
                }
            }

            @Override
            public void onFailure(Call<IsAttentionBean> call, Throwable t) {

            }
        });

    }

    //关注培训
    private void collectTrain(){
        TrainModel trainModel=new TrainModel();
        Call<AttentionBean> callCollectTrain=trainModel.userCollectTrain(u_id, t_id);
        callCollectTrain.enqueue(new Callback<AttentionBean>() {
            @Override
            public void onResponse(Call<AttentionBean> call, Response<AttentionBean> response) {
                if ("yes".equals(coresult)) {
                    Toast.makeText(TrainDetailActivity.this, "取消成功", Toast.LENGTH_SHORT).show();
                    collect.setImageResource(R.drawable.ic_collect_hui);
                }
                else{
                    Toast.makeText(TrainDetailActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                    collect.setImageResource(R.drawable.ic_collect_red);
                }
                refresh();
            }

            @Override
            public void onFailure(Call<AttentionBean> call, Throwable t) {

            }


        });
    }

    private void refresh(){
        isBeCollected();
    }
}

